// 基础配置

// const baseConfig = 'http://localhost:8080' + '/bole'
const baseConfig="https://www.bigpigbig.cn/stage-api"+'/bole'
/**
 * 账号密码登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @param {function} callback - 登录成功回调
 */
export const login = (username, password, callback) => {
  wx.showLoading({ title: '登录中...', mask: true })
  
  wx.request({
    url: `${baseConfig}/login`,
    data: { username, password },
    method: 'POST',
    header: { 'content-type': 'application/json' },
    success: (res) => {
      const { token, code: responseCode, user: userInfo } = res.data
      console.log(res)
      if (responseCode === 200) {
        saveToken(token, userInfo)
        
        wx.switchTab({
          url: '/pages/home/home'
        })
        
        callback && callback()
      } else {
        console.log(res)
        wx.showToast({ title: res.data.msg || '登录失败', icon: 'error' })
      }
    },
    fail: (err) => {
      console.error('登录请求失败:', err)
      wx.showToast({ title: '登录服务器失败！', icon: 'error' })
    },
    complete: () => {
      wx.hideLoading()
    }
  })
}

/**
 * 微信登录
 * @param {function} callback - 回调函数
 */
export const wxlogin = (callback) => {
  wx.showLoading()
  
  wx.login({
    success: (res) => {
      if (res.code) {
        const { miniProgram } = wx.getAccountInfoSync()
        
        wx.request({
          url: `${baseConfig}/wxlogin`,
          data: {
            code: res.code,
            appId: miniProgram.appId
          },
          method: 'POST',
          header: { 'content-type': 'application/json' },
          success: (res) => {
            const { data, code: responseCode, wxInfo, authInfo, token } = res.data
            
            if (responseCode === 200) {
              const { wxInfo = {}, userInfo = {} } = res.data
              console.log('登录成功:', token, userInfo)
              
              saveToken(token, userInfo)
              
              wx.switchTab({
                url: '/pages/home/home'
              })
            } else {
              console.error('微信登录失败:', res)
              wx.showToast({ title: '登录失败 请重试', icon: 'error' })
            }
          },
          fail: (err) => {
            console.error('微信登录请求失败:', err)
            wx.showToast({ title: '登录服务器失败！', icon: 'error' })
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      } else {
        console.error('获取登录凭证失败:', res.errMsg)
        wx.showToast({ title: '登录失败，请重试', icon: 'error' })
        wx.hideLoading()
      }
    },
    fail: (err) => {
      console.error('微信登录失败:', err)
      wx.showToast({ title: '登录失败，请重试', icon: 'error' })
      wx.hideLoading()
    }
  })
}

/**
 * 更新用户信息
 */
export const updateUserInfo = async () => {
  try {
    const userId = wx.getStorageSync('userId')
    const { data: userInfo } = await http.get(`/bole/userinfo/${userId}`)
    
    wx.setStorageSync('userInfo', userInfo)
    console.log('更新用户信息成功:', userInfo)
  } catch (error) {
    console.error('更新用户信息失败:', error)
  }
}

/**
 * 保存token和用户信息到本地存储
 * @param {string} token - 认证token
 * @param {object} userInfo - 用户信息
 */
const saveToken = (token, userInfo) => {
  console.log('保存用户信息:', userInfo)
  
  wx.setStorageSync('userId', userInfo.userId)
  wx.setStorageSync('userInfo', userInfo)
  wx.setStorageSync('token', token)
}

/**
 * 获取认证token
 * @returns {string|null} - 返回带Bearer前缀的token，或null
 */
export const getToken = () => {
  const authInfo = wx.getStorageSync('userInfo')
  const token = wx.getStorageSync('token')
  
  if (authInfo && token) {
    return 'Bearer ' + token
  }
  
  return null
}

/**
 * 移除用户相关信息
 * @param {function} callback - 回调函数
 */
export const removeUserInfo = (callback) => {
  wx.showLoading({ title: '退出中...' })
  
  wx.removeStorage({
    key: 'wxInfo',
    success: () => {
      wx.removeStorage({
        key: 'authInfo',
        success: (res) => {
          callback && callback(res)
          wx.showToast({ title: '退出成功！', icon: 'success' })
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    }
  })
}